<template>
  <div class="health-info-list-page">
    <van-nav-bar
      title="健康资讯"
      left-arrow
      @click-left="router.back()"
    />
    
    <!-- 分类标签 -->
    <div class="category-scroll">
    <div class="category-tabs">
        <div 
          v-for="category in categories" 
          :key="category.id" 
          class="category-item"
          :class="{ active: activeCategory === category.id }"
          @click="activeCategory = category.id"
        >
          {{ category.name }}
        </div>
      </div>
    </div>
    
    <!-- 文章列表 -->
    <div class="article-list">
      <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
        <van-list
          v-model:loading="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="loadMore"
        >
          <div 
            v-for="article in articleList" 
            :key="article.id" 
            class="article-item"
            @click="goToDetail(article.id)"
          >
            <div class="article-content">
            <div class="article-title">{{ article.title }}</div>
              <div class="article-desc">{{ formatContent(article.content) }}</div>
            <div class="article-meta">
                <div class="author-info">
                  <span class="author-name">{{ article.authorName || '匿名用户' }}</span>
                  <span class="publish-time">{{ formatTime(article.createdAt) }}</span>
                </div>
              <div class="stats">
                  <span class="view-count"><van-icon name="eye-o" /> {{ article.viewCnt }}</span>
                <span class="like-count"><van-icon name="like-o" /> {{ article.likeCnt }}</span>
                </div>
              </div>
            </div>
          </div>
          
          <div v-if="articleList.length === 0 && !loading && !refreshing" class="empty-state">
            <van-empty description="暂无内容" />
          </div>
        </van-list>
      </van-pull-refresh>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import { axiosrnewmedical } from '@/http/axiosRead';

// 定义分类接口
interface Category {
  id: number;
  name: string;
  sort: number;
}

// 定义文章信息接口
interface HealthArticle {
  id: number;
  catId: number;
  categoryName: string;
  title: string;
  content?: string;
  authorId?: number;
  authorName?: string;
  likeCnt: number;
  viewCnt: number;
  status?: string;
  createdAt?: string;
  tags?: string;
  imageUrl?: string;
}

const router = useRouter();
const categories = ref<Category[]>([]);
const activeCategory = ref<number>(1); // 默认选中第一个分类
const articleList = ref<HealthArticle[]>([]);
const pageIndex = ref(1);
const pageSize = 10;
const loading = ref(false);
const finished = ref(false);
const refreshing = ref(false);

// 获取分类列表
const fetchCategories = async () => {
  try {
    const res = await axiosrnewmedical.get('/Consult/categories');
    if (res.data && res.data.code === 200) {
      // 直接使用API返回的分类数据
      categories.value = res.data.data;
    } else {
      // 如果接口失败，使用默认分类
      categories.value = [
        { id: 1, name: '中医常识', sort: 1 },
        { id: 2, name: '健康养生', sort: 2 },
        { id: 3, name: '疾病预防', sort: 3 },
        { id: 4, name: '出院宣教', sort: 4 }
      ];
    }
  } catch (error) {
    console.error('获取分类失败:', error);
    // 使用默认分类
    categories.value = [
      { id: 1, name: '中医常识', sort: 1 },
      { id: 2, name: '健康养生', sort: 2 },
      { id: 3, name: '疾病预防', sort: 3 },
      { id: 4, name: '出院宣教', sort: 4 }
    ];
  }
};

// 获取文章列表
const fetchArticles = async () => {
  if (refreshing.value) {
    articleList.value = [];
    pageIndex.value = 1;
    finished.value = false;
  }

  try {
    const params: {
      pageIndex: number;
      pageSize: number;
      catId?: number;
    } = {
      pageIndex: pageIndex.value,
      pageSize
    };
    
    // 添加分类过滤
    params.catId = activeCategory.value;
    
    const res = await axiosrnewmedical.get('/Consult/questions', { params });
    if (res.data && res.data.code === 200) {
      const newArticles = res.data.data.items || [];
      
      // 如果是刷新，替换所有文章
      if (refreshing.value) {
        articleList.value = newArticles;
        refreshing.value = false;
      } else {
        // 否则添加新文章
        articleList.value = [...articleList.value, ...newArticles];
      }
      
      // 如果返回的文章少于pageSize或者已经到了最后一页，表示已经没有更多了
      const totalPages = res.data.data.totalPages || 1;
      if (newArticles.length < pageSize || pageIndex.value >= totalPages) {
        finished.value = true;
      } else {
        pageIndex.value++;
      }
    } else {
      // 如果接口失败，使用模拟数据
      const mockArticles = generateMockArticles(activeCategory.value, pageIndex.value);
      
      if (refreshing.value) {
        articleList.value = mockArticles;
        refreshing.value = false;
      } else {
        articleList.value = [...articleList.value, ...mockArticles];
      }
      
      if (mockArticles.length < pageSize) {
        finished.value = true;
      } else {
        pageIndex.value++;
      }
    }
  } catch (error) {
    console.error('获取文章列表失败:', error);
    // 使用模拟数据
    const mockArticles = generateMockArticles(activeCategory.value, pageIndex.value);
    
    if (refreshing.value) {
      articleList.value = mockArticles;
      refreshing.value = false;
    } else {
      articleList.value = [...articleList.value, ...mockArticles];
    }
    
    if (mockArticles.length < pageSize) {
      finished.value = true;
    } else {
      pageIndex.value++;
    }
  } finally {
    loading.value = false;
  }
};

// 生成模拟文章数据
const generateMockArticles = (catId: number, page: number): HealthArticle[] => {
  const mockData = [
    {
      id: 1,
      catId: 1,
      categoryName: '中医常识',
      title: '揉背治病的穴位，小儿揉背可以治什么病',
      content: '中医按摩是一种传统的治疗方法，通过刺激特定的穴位来调理身体，小儿揉背可以治疗多种疾病...',
      authorName: '张医生',
      likeCnt: 520,
      viewCnt: 2000,
      createdAt: '2020-01-01',
      tags: '中医常识'
    },
    {
      id: 2,
      catId: 1,
      categoryName: '中医常识',
      title: '菱角的功效与作用',
      content: '菱角是一年生草本水生植物菱的果实，菱角皮脆肉美，蒸煮后剥壳食用，亦可熬粥。菱角含有丰富的蛋白质、不饱和脂肪酸及多种维生素和微量元素，具有利尿通乳，止渴，解酒毒的功效...',
      authorName: '刘医生',
      likeCnt: 520,
      viewCnt: 2000,
      createdAt: '2020-01-01',
      tags: '中医常识'
    },
    {
      id: 3,
      catId: 1,
      categoryName: '中医常识',
      title: '虚不受补者冬天怎么食补？',
      content: '中医认为虚不受补是指体质虚弱的人不能接受大补的药物或食物，容易出现上火、消化不良等症状...',
      authorName: '王医生',
      likeCnt: 520,
      viewCnt: 2000,
      createdAt: '2020-01-01',
      tags: '中医常识'
    },
    {
      id: 4,
      catId: 1,
      categoryName: '中医常识',
      title: '自测是否脾虚 出现5个征兆说明你该补脾了',
      content: '脾虚是中医术语，泛指因脾气虚损引起的一系列脾脏生理功能失常的病理现象及病症...',
      authorName: '李医生',
      likeCnt: 520,
      viewCnt: 2000,
      createdAt: '2020-01-01',
      tags: '中医常识'
    }
  ];

  // 根据分类过滤文章
  const filteredData = mockData.filter(article => article.catId === catId);

  // 模拟分页
  const startIndex = (page - 1) * pageSize;
  const endIndex = startIndex + pageSize;
  
  return filteredData.slice(startIndex, endIndex);
};

// 格式化内容
const formatContent = (content?: string) => {
  if (!content) return '';
  // 移除HTML标签，只保留文本
  const text = content.replace(/<\/?[^>]+(>|$)/g, '');
  // 截取前50个字符
  return text.length > 50 ? text.substring(0, 50) + '...' : text;
};

// 格式化时间
const formatTime = (dateStr?: string) => {
  if (!dateStr) return '';
  try {
    const date = new Date(dateStr);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
  } catch {
    return dateStr;
  }
};

// 跳转到文章详情
const goToDetail = (id: number) => {
  router.push(`/health-info/detail/${id}`);
};

// 下拉刷新
const onRefresh = () => {
  refreshing.value = true;
  finished.value = false;
  fetchArticles();
};

// 加载更多
const loadMore = () => {
  if (!loading.value && !finished.value) {
    loading.value = true;
    fetchArticles();
  }
};

// 监听分类变化
watch(activeCategory, () => {
  articleList.value = [];
  pageIndex.value = 1;
  finished.value = false;
  loading.value = true;
  fetchArticles();
});

onMounted(() => {
  fetchCategories();
  loading.value = true;
  fetchArticles();
});
</script>

<style scoped>
.health-info-list-page {
  min-height: 100vh;
  background-color: #f8f9fa;
}

.category-scroll {
  overflow-x: auto;
  background-color: #fff;
  border-bottom: 1px solid #eee;
  position: sticky;
  top: 0;
  z-index: 10;
}

.category-tabs {
  display: flex;
  padding: 12px 8px;
  min-width: max-content;
}

.category-item {
  padding: 6px 12px;
  margin: 0 8px;
  font-size: 14px;
  color: #666;
  border-radius: 16px;
  white-space: nowrap;
  cursor: pointer;
  transition: all 0.3s;
}

.category-item.active {
  background-color: #338aff;
  color: #fff;
}

.article-list {
  padding: 12px;
}

.article-item {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 12px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.04);
}

.article-content {
  display: flex;
  flex-direction: column;
}

.article-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 8px;
  line-height: 1.4;
}

.article-desc {
  font-size: 14px;
  color: #666;
  margin-bottom: 12px;
  line-height: 1.5;
  overflow: hidden;
  text-overflow: ellipsis;
}

.article-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #999;
}

.author-info {
  display: flex;
  align-items: center;
}

.author-name {
  margin-right: 8px;
  color: #666;
}

.stats {
  display: flex;
  gap: 16px;
}

.like-count, .view-count {
  display: flex;
  align-items: center;
  gap: 4px;
}

.empty-state {
  padding: 32px 0;
}
</style> 